package com.fenghuajueli.libbasecoreui.mvp;

import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.Nullable;

public abstract class LifecycleBaseFragment<P extends BasePresenter> extends BaseFragment implements BaseView {
    private View contentView;
    private Context context;
    protected P presenter;
    private boolean currentVisibleState = false;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = getActivity().getApplicationContext();
    }

    public abstract P initPresenter();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        contentView = LayoutInflater.from(getActivity()).inflate(getContentViewId(), container, false);
        presenter = initPresenter();
        presenter.attachView(this);
        //fragment需要在单独添加一次生命周期监听
        getLifecycle().addObserver(presenter);
        initView(savedInstanceState);
        return contentView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        contentView = null;
        if (presenter != null) {
            presenter.detachView();
        }
    }

    public View getContentView() {
        return contentView;
    }

    public Context getApplicationContext() {
        return context;
    }

    public abstract void initView(Bundle savedInstanceState);

    public abstract int getContentViewId();

    public View findViewById(int id) {
        if (contentView != null)
            return contentView.findViewById(id);
        return null;
    }


    @Override
    public void onResume() {
        super.onResume();
        //新版本
        if (!isHidden() && !currentVisibleState && isResumed()) {
            currentVisibleState = true;
            dispatchUserVisibleHint(true);
        }
    }

    /**
     * 当前界面可见不可见
     *
     * @param isVisible
     */
    protected void dispatchUserVisibleHint(boolean isVisible) {

    }

    @Override
    public void onPause() {
        super.onPause();
        if (currentVisibleState && !isResumed()) {
            currentVisibleState = false;
            dispatchUserVisibleHint(false);
        }
    }

    @Override
    public void showLoading() {
        showLoadingDialog();
    }

    @Override
    public void showLoading(String tips) {
        showLoadingDialog(tips);
    }

    @Override
    public void showShortToast(String tipsContent) {

    }

    @Override
    public void showLongToast(String tipsContent) {

    }

    @Override
    public void showEmptyContentView() {

    }

    @Override
    public void showEmptyContentView(String content) {

    }

    @Override
    public void hideLoading() {
        hideLoadingDialog();
    }
}
